<template>
  <div class="login-page">
    <el-form label-width="65px">
      <el-form-item label="验证码">
        <el-input placeholder="请输入验证码" v-model="sidentifyMode" clearable></el-input>
      </el-form-item>
      <!-- 使用验证码组件 -->
      <div class="code" @click="refreshCode">
        <SIdentify :identifyCode="identifyCode"></SIdentify>
      </div>
      <el-button class="login_btn" type="primary" size="default" @click="login">登录</el-button>
    </el-form>
  </div>
</template>
 
<script setup>
import SIdentify from '@/components/Sidentify'
import { ElMessage } from 'element-plus'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
//获取路由器
let $router = useRouter()
let sidentifyMode = ref('') //输入框验证码
let identifyCode = ref('') //图形验证码
let identifyCodes = ref('1234567890abcdefjhijklinopqrsduvwxyz') //验证码出现的数字和字母
 
//组件挂载
onMounted(() => {
  identifyCode.value = ''
  makeCode(identifyCodes.value, 4)
})
 
// 生成随机数
const randomNum = (min, max) => {
  max = max + 1
  return Math.floor(Math.random() * (max - min) + min)
}
// 随机生成验证码字符串
const makeCode = (o, l) => {
  for (let i = 0; i < l; i++) {
    identifyCode.value += o[randomNum(0, o.length)]
  }
}
// 更新验证码
const refreshCode = () => {
  identifyCode.value = ''
  makeCode(identifyCodes.value, 4)
}
//登录
const login = () => {
  //验证验证码不为空
  if (!sidentifyMode.value) {
    ElMessage({ type: 'error', message: '验证码不能为空！' })
    return
  }
  //验证验证码是否正确
  if (sidentifyMode.value != identifyCode.value) {
    ElMessage({ type: 'error', message: '验证码错误' })
    refreshCode()
    return
  } else {
    ElMessage({ type: 'success', message: '登录成功' })
    $router.push('/home')
  }
}
</script>
 
<style lang="scss" scoped>
.login-page {
  border: 1.5px solid rgb(123, 109, 30);
  border-radius: 8px;
  width: 400px;
  margin: 0 auto;
  margin-top: 50px;
  padding: 20px;
  .code {
    text-align: center;
    margin-bottom: 10px;
  }
  .login_btn {
    width: 100%;
  }
}
</style>